<template>
	<view>
		<view class="entry-page container">
		  <!-- 已获取微信用户信息 -->
		  <view class="header">
			<image class="user-avatar"
			  :src="userInfo.avatar"/>
			<view class="user-identity">
			  <text class="wechat-nickname">{{userInfo.username}}</text>
			  <view v-if="doubanAuth.access_token" class="douban-status">
				<text class="douban-label">douban</text>
				<text>{{doubanAuth.douban_user_name}}</text>  
			  </view>
			  <navigator v-else class="douban-status" url="/pages/fm/login" open-type="navigate">
				<text class="douban-label warning">尚未绑定FM账户</text>
			  </navigator>
			</view>
			<view class="user-actions">
			  <navigator url="/pages/fm/login" open-type="navigate" class="icon icon-cog"></navigator>
			</view>
		  </view>
		  <view class="content">
			<view v-for="(group, i) in doubanRadio.groups" :key="i" 
				class="channel-group" :class="[group.chls.length]" v-if='group.chls.length'>
			  <view v-if="group.group_name !== ''" class="channel-group-title">
					<text class="channel-group-name">{{group.group_name}}</text>
			  </view>
			  <view class="channel-list">
				<block v-for="(channel, j) in group.chls" :key="j">
				  <view class="channel" v-bind:class="[doubanRadio.active == channel.id ? 'active-channel': '' ]"
					@click="handleSwitchChannel(channel)" :data-channel-id="channel.id">
					<image class="channel-cover" :src="channel.cover" />
					<text class="channel-name channel-mhz">{{channel.name}}</text>
				  </view>
				</block>
			  </view>
			</view>
		  </view>

		  <!-- 底部播放器 -->
		  <view class="player-footer" v-bind:style="{marginBottom: footerMarginBottom + 'upx'}">
			<view class="player-footer__circle-progress__container"
				v-bind:class="[playState.isPlaying ? 'playing': '' ]" @click="handleClickCover()">
			  <image class="player-footer__cover" :src="playing.cover"></image>
			  <view class="player-footer__circle-progress__left-wrapper">
					<view class="player-footer__circle-progress__left-inner-circle"
					 v-bind:style="{transform:'rotate(' + playState.leftRotate + 'deg)'}">
					</view>
			  </view>
			  <view class="player-footer__circle-progress__right-wrapper">
					<view class="player-footer__circle-progress__right-inner-circle"
					v-bind:style="{transform:'rotate(' + playState.rightRotate + 'deg)'}">
					</view>
			  </view>
			</view>
			<navigator class="player-footer__intro"
			  url="/pages/fm/detail"
			  open-type="navigate">
			  <view class="player-footer__title"><text class="player-footer__title__text">{{playing.title}} - {{playing.artist}}</text></view>
			  <text class="player-footer__channel_name">{{playing.channelName}}</text>
			</navigator>
			<button class="player-footer__douban-icon-heart"
				v-bind:class="[playing.like ? 'player-footer__douban-icon-heart--active': '' ]"
			  catchtap="handleToggleHeart">
			</button>
			<button class="player-footer__douban-icon-next" @click="handlePlayNextSong()"></button>
		  </view>
		</view>

	</view>
</template>

<script>
	import service from '../../common/service.js';
	var innerAudioContext;
	var channel_groups_hiden = [1];//group_id:1  从艺术家出发
	export default {
		data() {
			return {
				userInfo:{
					username:'bukaa',
					authorized: false,
					avatar:'../../static/img/common/avatar.png',
				},
				doubanAuth:{},
				doubanRadio:{
					groups:[]
				},
				playintProcessListeningerId: null,
				songs:this.$fm.songs,
				playing: this.$fm.playing,
				playState:this.$fm.playState,
				channel: this.$fm.channel,
				maxRequestReconnectTime:5,
				currRequestReconnectTime: 1,
				footerMarginBottom: 0,
				channel_cache_key: 'fm_channel_cache',
			};
		},
		onLoad() {
			this.init();
		},
		methods:{
			init() {
				var that = this;
				uni.setNavigationBarTitle({title:"FM"});
				//设置footer样式
				// #ifdef H5
				that.footerMarginBottom = '100';
				// #endif
				//初始化播放器对象
				if(!that.$fm.innerAudioContext){
					that.$fm.innerAudioContext = uni.createInnerAudioContext();
					//当前播放结束，播放下一曲
					that.$fm.innerAudioContext.onEnded(()=>{
						console.log("the end.......");
						setTimeout(function(){
							that.handlePlayNextSong();
						},500);
					});
					that.$fm.innerAudioContext.onError(()=>{
						uni.showToast({
							title:'加载出错，播放下一曲',
							success:function() {
								setTimeout(function(){
									that.handlePlayNextSong();
								},500);
							}
						})
					});
					that.$fm.innerAudioContext.onCanplay(() => {
						//初始化duration
						that.playing.audioDuration = innerAudioContext.duration
						setTimeout(function() {
							//延时获取音频真正的duration
							var duration = innerAudioContext.duration;
							var min = parseInt(duration / 60);
							var sec = parseInt(duration % 60);
							if (min.toString().length == 1) {
								min = `0${min}`;
							}
							if (sec.toString().length == 1) {
								sec = `0${sec}`;
							}
							//设置真实时长
							that.playing.audioDuration = innerAudioContext.duration
							// t.showTime2 = `${min}:${sec}`
						}, 100);
					});
				}
				innerAudioContext = that.$fm.innerAudioContext;
				//获取用户基本信息
				that.userinfo={
					avatar:'../../static/img/common/avatar.png'
				};
				var userInfo = service.getUsers();
				if(userInfo){
					that.userInfo = userInfo;
				}
				that.doubanAuth = service.getDoubanAuth();
				//获取channels
				that.getChannels();
				//监听播放进度
				that.playintProcessListeningerId = setInterval(function(){
						var cr = innerAudioContext.currentTime;
						if(!that.playing.audioDuration)
							return;
						if(cr*2 < that.playing.audioDuration){
								that.playState.rightRotate = 225 + (cr*2 / that.playing.audioDuration) * 180;
								that.playState.leftRotate = 225;
						}else{
							that.playState.rightRotate = 405;
								that.playState.leftRotate = 225 + (cr*2 / that.playing.audioDuration - 1) * 180;
						}
						that.$fm.playState = that.playState;
						
						var lyric = that.playing.lyric;
						if(lyric && lyric.length > 0){
							if(lyric[that.playing.lyricIdx] && lyric[that.playing.lyricIdx].key >= cr){
								if(that.playing.lyricIdx >1){
									that.playing.preLyric = lyric[that.playing.lyricIdx-2].value;
								}else{
									that.playing.preLyric = that.playing.title;
								}
								if(that.playing.lyricIdx < lyric.length-1){
									that.playing.afterLyric = lyric[that.playing.lyricIdx].value;
								}
								if(that.playing.lyricIdx >0){
									that.playing.curLyric = lyric[that.playing.lyricIdx-1].value;
								}
							}else{
								that.playing.lyricIdx +=1;
							}
							that.$fm.playing.preLyric = that.playing.preLyric;
							that.$fm.playing.afterLyric = that.playing.afterLyric;
							that.$fm.playing.curLyric = that.playing.curLyric;
						}
				}, 400);
			},
			getChannels(){
				var that = this;
				//先从缓存中获取
				that.doubanRadio = uni.getStorageSync(that.channel_cache_key);
				if(that.doubanRadio){
					that.initFirstSong();
				}
				var url = "https://bukaa.cn/api-cms/fm/douban/channels";
				if(that.doubanAuth && that.doubanAuth.access_token){
					url += ("?token=" + that.doubanAuth.access_token);
				}
				uni.request({
					url: url,					
					method:'GET',
					success: (res) => {
						if(res.statusCode === 200 && res.data.data){
							that.doubanRadio = res.data.data;
							if(that.doubanRadio.groups){
								channel_groups_hiden.forEach(function(gid){
									that.doubanRadio.groups.removeByFieldAndId('group_id', gid);
								});
								var chls = that.doubanRadio.groups[0].chls;
								if(chls){
									chls.forEach(function(ch){
										if(ch.cover && ch.cover.indexOf("channel_selected_cover")>0)
											ch.cover = "../../static/img/fm/channel_selected_cover.png";
										else if(ch.cover && ch.cover.indexOf("default_personal_channel_cover")>0)
											ch.cover = "../../static/img/fm/default_personal_channel_cover.png";	
									});
								}
							}
							that.initFirstSong();
							//缓存最新的channel列表
							uni.setStorage({
								key:that.channel_cache_key,
								data:that.doubanRadio
							})
						}
					}
				})
			},
			/**
			 * 获取播放歌曲列表
			 * channel: 当前channel
			 * play: 是否立即播放
			 */
			getPlayList(channel){
				var that = this;
				that.channel = channel;
				that.$fm.channel  = that.channel;
				that.$fm.songs = [];
				that.$fm.doubanRadio = [];
				uni.showLoading({
					title:"loading..."
				})
				var url = 'https://bukaa.cn/api-cms/fm/douban/playlist/' + channel.id;
				if(that.doubanAuth && that.doubanAuth.access_token){
					url += ("?token=" + that.doubanAuth.access_token);
				}
				uni.request({
					url: url,					
					method:'GET',
					success: (res) => {
						uni.hideLoading();
						if(res.statusCode === 200 && res.data.data){
							that.songs = res.data.data.song;
							that.songs = that.songs.filter(function(s){
								return s['url'] && s['url'].indexOf('.mp4') >0;
							});
						}
						if(that.songs.length >0){
							that.currRequestReconnectTime = 1;
							that.$fm.songs = that.songs;
							that.playing = {
								channelName:channel['name'],
								cover:channel['cover'],
							},
							that.doubanRadio.active = channel.id;
							that.play(this.songs.pop());
						}else{
							if(that.currRequestReconnectTime >= that.maxRequestReconnectTime){
								that.currRequestReconnectTime = 1;
								uni.showToast({
									title:'no song!!!',
								})
							}else{
								that.currRequestReconnectTime++;
								that.getPlayList(channel);
							}
							
						}
					},complete: () => {
						uni.hideLoading();
					}
				})
			},
			onPullDownRefresh(event){
				var that = this;
				uni.request({
					url:'https://bukaa.cn/api-cms/fm/douban/channels',					
					method:'GET',
					success: (res) => {
						if(res.statusCode === 200 && res.data.data){
							that.doubanRadio = res.data.data;
							that.initFirstSong();
							//缓存最新的channel列表
							uni.setStorage({
								key:that.channel_cache_key,
								data:that.doubanRadio
							})
						}
					}
				})
			},
			//初始播放第一首
			initFirstSong(){
				var that = this;
				if(that.doubanRadio && that.doubanRadio.groups[0]){
					var g = that.doubanRadio.groups[0];
					//that.getPlayList(g['chls'][0]);
				}
			},
			//切换分类
			handleSwitchChannel(channel) {
				return this.getPlayList(channel);
			},
			/**
			 * 播放
			 * song: 当前歌曲
			 */
			play(song){
				if(!song|| !song.url)
					return;
				var that = this;
				that.playState.rightRotate = 225;
				that.playState.leftRotate = 225;
				//更新当前歌曲信息
				that.playing.title=song['title'];
				that.playing.artist=song['artist'];
				that.playing.cover=song['picture'];
				that.playing.like=song['like'];
				that.playing.singerAvatar = song['singers'] ? song['singers'][0]['avatar'] : '';
				//重置部分数据
				that.playing.audioDuration = 0;
				that.playing.lyricIdx = 0;
				that.playing.curLyric = "";
				that.playing.preLyric = "";
				that.playing.afterLyric = "";
				this.$fm.playing = that.playing;
				//设置src
				innerAudioContext.src = song.url;
				//运行一次
				innerAudioContext.play();
				//修改状态
				that.playState.isPlaying = true;
				that.$fm.playState = that.playState;
				//innerAudioContext.pause();
				that.getLyric(song);
			},
			getLyric(song){
				var that = this;
				that.$fm.playing.lyric = null;
				that.playing.lyric = null;
				
				var url =  "https://bukaa.cn/api-cms/fm/douban/lyric";
				var data = {"sid": song.sid, "ssid": song.ssid};
				uni.request({
					url:url,
					data: data,
					success: (res) => {
						if(res.statusCode === 200 && res.data.data){
							var lyric = res.data.data.lyric;
							//拆分成单个句子
							var lys = lyric.split("[");
							//生成K，V
							var lyricArr = [];
							if(lys && lys.length > 0){
								lys.forEach(function(ly){
									if(ly && ly.indexOf("]")>0){
										var t = ly.substring(0, ly.indexOf("]"));
										var val = ly.substring(ly.indexOf("]")+1).replace("\n","").trim();
										if(val && val.length > 0)
											lyricArr.push({key: t.substring(0,t.indexOf(":")) * 60 + parseFloat(t.substring(t.indexOf(":")+1)), value: ly.substring(ly.indexOf("]")+1)});
									}	
								})
								lyricArr.sort(function(e1, e2){return e1.key - e2.key});
								that.playing.lyric = lyricArr;
								that.$fm.playing.lyric = lyricArr;
								//标记当前歌词位置
								that.$fm.playing.lyricIdx = 0;
							}
						}
					}
				})
			},
			//播放下一首
			handlePlayNextSong(){
				var that = this;
				if(that.songs.length == 1){
					that.getPlayList(that.channel);
					that.play(that.songs.pop());
				}else if(that.songs.length == 0){
					that.getPlayList(that.channel);
					uni.showLoading({
						title:'loading...'
					})
					setTimeout(function(){
						uni.hideLoading();
						that.handlePlayNextSong();
					}, 1000)
				}else {
					that.play(that.songs.pop());
				}
			},
			//点击cover（暂停或继续）
			handleClickCover() {
				if(this.playState.isPlaying){
					innerAudioContext.pause();
				}else{
					innerAudioContext.play();
				}
				this.playState.isPlaying = !this.playState.isPlaying;
			},
			handleStop(){
				innerAudioContext.stop();
				this.playState.isPlaying = false;
			},
			handleToggleHeart(like) {
				if (like) {
					this.removeHeart({
						songId: id,
						progress: current / duration * 100
					});
				} else {
					this.addHeart({
						songId: id,
						progress: current / duration * 100
					});
				}
			},
		}
	}
</script>

<style>
@import url("../../static/css/fm.css");
.circle-img {
  border-radius: 50%;
}
.text-overfolw {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
.all-center {
  position: absolute;
  transform: translate(-50%, -50%);
  left: 50%;
  top: 50%;
}
.override-btn {
  margin: 0 0 0 12px !important;
  padding: 0 !important;
  box-sizing: border-box;
  background: transparent;
}
.override-btn::after {
  width: inherit;
  position: relative;
  top: auto;
  left: auto;
  border: none;
  transform: scale(1);
  border-radius: 0;
}
@keyframes rotate-90 {
  0% {
    transform: rotate(270deg);
  }
  50% {
    transform: rotate(315deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
.entry-page {
  background-color: #f5f5f5;
  font-family: -apple-system-font, "Helvetica Neue", sans-serif;
}
.entry-page .form .input {
  background-color: #fff;
}
.entry-page .paragraph.comment {
  font-size: 14px;
  text-align: right;
}
.entry-page .header {
  background-color: #fcfcfc;
  width: 100%;
  margin: 0 -32rpx;
  padding: 0 32rpx;
  height: 160rpx;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  transform: translate(0, -10rpx);
  transition: all ease-in-out 0.3s;
  position: relative;
  z-index: 999;
  box-shadow: 2rpx 2rpx 2rpx 0 rgba(75, 75, 75, 0.2);
  margin-top: 20rpx;
}
.entry-page .header .user-avatar {
  width: 96rpx;
  height: 96rpx;
  border-radius: 6rpx;
  border: 1px solid #f5f5f5;
}
.entry-page .header .user-identity {
  display: flex;
  margin-left: 16px;
  flex-direction: column;
}
.entry-page .header .user-identity .wechat-nickname {
  font-size: 16px;
  color: #616161;
  line-height: 20px;
}
.entry-page .header .user-identity .douban-status {
  font-size: 12px;
  color: #acacab;
  margin-top: 4px;
  line-height: 20px;
}
.entry-page .header .user-identity .douban-label {
  color: #63c284;
  padding: 2px 4px;
  margin-right: 4px;
  border: 1px solid #63c284;
  border-radius: 3px;
}
.entry-page .header .user-identity .douban-label.warning {
  color: #977e42;
  border: none;
  background: transparent;
  padding: 4px 0;
}
.entry-page .header .user-actions {
  display: flex;
  margin-left: 32rpx;
  justify-content: flex-end;
  flex-grow: 1;
  transform: translate(0, 0rpx);
  transition: transform ease-in-out 0.3s;
}
.entry-page .header .user-actions .icon {
  font-size: 20px;
  margin: 0 0 0 8rpx;
  padding: 8px;
  color: #616161;
  background: transparent;
  border: none;
}
.entry-page .header .user-actions .icon::after {
  display: none;
}
.entry-page .content {
  transition: all ease-in-out 0.3s;
  flex-grow: 1;
  margin-bottom: 136rpx;
}
.entry-page.authorized .header {
  transform: translate(0, 0);
}
.entry-page.authorized .header .user-actions {
  transform: translate(0, 0);
}
.entry-page.authorized .header .user-actions .icon.icon-cog {
  animation: rotate-90 0.3s linear;
}

</style>
